package com.ambitor.ipro.actions;

import java.sql.SQLException;
import java.util.Map;

import org.apache.struts2.json.annotations.JSON;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.entities.InstallSetting;
import com.ambitor.ipro.entities.Result;
import com.ambitor.ipro.entities.UserProValidFlag;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.PropertiesReader;
import com.ambitor.ipro.util.ResultCode;
import com.ambitor.ipro.util.Utils;

public class PreInstallAction extends BaseAction {

	private static final long serialVersionUID = 4377605422827859644L;

	private transient Map<String, String> ipro;

	private transient SuperDao superDao = null;

	private transient TopService topService;

	private Result result = new Result();;

	public PreInstallAction() throws SQLException {
		superDao = new SuperDaoImpl(pd.getConn());
		topService = new TopService(Constants.EVN_SWITCH,
				Constants.APP_KEY_IPROMOTION, Constants.APP_SECRET_IPROMOTION);
	}

	@JSON(serialize = false)
	public Map<String, String> getIpro() {
		return ipro;
	}

	public void setIpro(Map<String, String> ipro) {
		this.ipro = ipro;
	}

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	@SuppressWarnings("unchecked")
	public String preInstall() {
		try {
			// boolean isPass =
			validateInstallNum();
			// if (isPass) {
			// preValidateConflict();
			// }
		} catch (Exception e) {
			result.setCode(ResultCode.ERROR);
			result.setMsg("系统出现错误，请联系我们");
			logger.error("预安装过程中出现异常", e);
		}
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public void preValidateConflict() throws Exception {
		String place = ipro.get("install_place");
		IData param = new DataMap();
		param.put("USER_ID", pd.getTopUserId());
		param.put("VALID_FLAG", UserProValidFlag.VALID);
		String sql = "select * from TF_P_USER_PRO_BATCH where user_id =:USER_ID"
				+ " and valid_flag =:VALID_FLAG and frequency>0";
		IDataset userPros = superDao.queryListBySql(sql, param);
		if (userPros.size() == 0) {// 没有老配置
			result.setCode(ResultCode.SUCCESS);
		} else {
			/*
			 * 遍历现有的配置，找到是否有冲突，不能继续安装的
			 */
			for (int i = 0; i < userPros.size(); i++) {
				IData userPro = userPros.getData(i);
				if (!place.contains(userPro.getString("INSTALL_PLACE")))
					continue;
				String flag = _validate(userPro);
				if ("0".equals(flag)) {
					String installSetting = userPro
							.getString("INSTALL_SETTING");
					String msg = "您之前已经为"
							+ getInstallSettingName(installSetting)
							+ "设置了推广规则，当前操作无法继续，请先到[我要卸载]页面卸载之前的设置";
					result.setCode(ResultCode.ERROR);
					result.setMsg(msg);
					return;
				}
			}

			/*
			 * 遍历现有的配置，找到是否有冲突，可以继续并覆盖原来配置的
			 */
			for (int i = 0; i < userPros.size(); i++) {
				String flag = _validate(userPros.getData(i));
				IData userPro = userPros.getData(i);
				if (!place.contains(userPro.getString("INSTALL_PLACE")))
					continue;
				if ("1".equals(flag)) {
					String installSetting = userPro
							.getString("INSTALL_SETTING");
					String msg = "您之前已经为"
							+ getInstallSettingName(installSetting)
							+ "设置了推广规则，本次操作可能会覆盖之前的设置，您确认将继续吗？";
					result.setCode(ResultCode.SUCCESS);
					result.setMsg(msg);
					return;
				}
			}
			result.setCode(ResultCode.SUCCESS);
			result.setMsg("验证通过，请点击点击按钮开始安装");
		}
	}

	/**
	 * 根据参数表里的配置来来判断是否有冲突
	 */
	@SuppressWarnings("unchecked")
	private String _validate(IData userPro) throws Exception {
		String newSetting = ipro.get("install_setting");
		String oldSetting = userPro.getString("INSTALL_SETTING");
		IData param = new DataMap();
		param.put("NEW_SETTING", newSetting);
		param.put("OLD_SETTING", oldSetting);
		IData data = superDao.queryByPK("TD_P_PRO_LIMIT", param);
		return data.getString("RESULT");
	}

	private String getInstallSettingName(String installSetting) {
		return "[" + InstallSetting.valueOf(installSetting).getChineseName()
				+ "]";
	}

	private boolean validateInstallNum() throws Exception {
		String installSetting = ipro.get("install_setting");
		long toPromoteNum = 0;
		if (installSetting.equals("all")) {
			toPromoteNum = topService.getAllItemsCount(pd.getTopSessionId(), pd
					.getTopNick());
		} else if (installSetting.equals("onSale")) {
			toPromoteNum = topService.getOnSaleItemsCount(pd.getTopSessionId(),
					pd.getTopNick());
		} else if (installSetting.equals("someCategory")) {
			String sellerCats = ipro.get("seller_cats");
			toPromoteNum = topService.getItemsCountOfSpecificCat(pd
					.getTopSessionId(), pd.getTopNick(), sellerCats);
		} else if (installSetting.equals("itemCategory")) {
			String itemCats = ipro.get("item_cats");
			toPromoteNum = topService.getOnsaleItemCountOfSpecificItemCat(pd
					.getTopSessionId(), pd.getTopNick(), itemCats);
		} else if (installSetting.equals("custom")) {
			toPromoteNum = Integer.parseInt(ipro.get("to_promote_num"));
		}
		Result versionInfo = pd.getTopUserSubscribe();
		int maxInstallItems = Utils.getMaxInstallItems(versionInfo.getCode());
		if (toPromoteNum > maxInstallItems) {
			result.setCode(ResultCode.ERROR);
			String resultMsg = "";
			if (versionInfo.getCode() == 3) {
				String contact = PropertiesReader.getString("WANGWANG_CONTACT");
				resultMsg = "一次最多允许安装推广模块到" + maxInstallItems
						+ "个宝贝上,有问题请给我们留言。" + contact;
			} else {
				String orderUrl = PropertiesReader.getString("IPRO_ORDER_URL");
				String url = "<a href='"
						+ orderUrl
						+ "' target='_blank' style='text-decoration:underline;color:blue'>建议订购更高的版本</a>";
				resultMsg = "您在第3步中选择了" + toPromoteNum + "个宝贝安装推广代码，但由于您是"
						+ versionInfo.getMsg() + "用户，一次最多允许把推广模块安装到"
						+ maxInstallItems + "个宝贝上，安装操作无法继续进行。" + url;
			}
			result.setMsg(resultMsg);
			return false;
		}
		result.setCode(ResultCode.SUCCESS);
		return true;
	}
}
